package com.zhuhjay.ruiji.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhuhjay.ruiji.common.BaseContext;
import com.zhuhjay.ruiji.common.R;
import com.zhuhjay.ruiji.domain.OrderDetail;
import com.zhuhjay.ruiji.domain.Orders;
import com.zhuhjay.ruiji.domain.dto.OrdersDto;
import com.zhuhjay.ruiji.service.IOrderDetailService;
import com.zhuhjay.ruiji.service.IOrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ZhuHJay
 * @date 2022/5/17 16:11
 */
@Slf4j
@RestController
@RequestMapping("order")
public class OrderController {

    private final IOrdersService ordersService;
    private final IOrderDetailService orderDetailService;
    public OrderController(IOrdersService ordersService, IOrderDetailService orderDetailService){
        this.ordersService = ordersService;
        this.orderDetailService = orderDetailService;
    }

    @PostMapping("submit")
    public R<String> submit(@RequestBody Orders orders){
        ordersService.submit(orders);
        return R.success("下单成功");
    }

    @GetMapping("list")
    public R<List<Orders>> list(){
        return R.success(ordersService.list(new LambdaQueryWrapper<Orders>()
                .eq(Orders::getUserId, BaseContext.getCurrent())));
    }

    @GetMapping("userPage")
    public R<Page<OrdersDto>> userPage(int page, int pageSize){
        // 获取所有订单数据
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>();
        ordersService.page(ordersPage, new LambdaQueryWrapper<Orders>()
                .eq(Orders::getUserId, BaseContext.getCurrent()));
        // 拷贝数据
        BeanUtils.copyProperties(ordersPage, ordersDtoPage, "records");
        // 补充订单明细
        List<OrdersDto> orderDetails = ordersPage.getRecords().stream().map(order -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(order, ordersDto);
            // 根据订单号查询所有的订单明细表
            ordersDto.setOrderDetails(orderDetailService.list(new LambdaQueryWrapper<OrderDetail>()
                    .eq(OrderDetail::getOrderId, order.getNumber())));
            return ordersDto;
        }).collect(Collectors.toList());
        ordersDtoPage.setRecords(orderDetails);
        return R.success(ordersDtoPage);
    }

    @PostMapping("again")
    public R<String> again(@RequestBody Orders orders){
        ordersService.again(orders);
        return R.success("下单成功");
    }

}
